<template>
  <div class="avatar-test">
    <h3>头像上传测试工具</h3>


    <div class="test-section">
      <h4>头像显示测试</h4>
      <div class="avatar-tests">
        <div class="avatar-test-item">
          <p>当前头像:</p>
          <el-avatar :size="80" :src="avatarUrl">
            {{ user?.nickname?.charAt(0) || 'U' }}
          </el-avatar>
        </div>

        <div class="avatar-test-item" v-if="user?.avatar">
          <p>直接API URL:</p>
          <el-avatar :size="80" :src="userAPI.getAvatarUrl(user.avatar || '')">
            {{ user?.nickname?.charAt(0) || 'U' }}
          </el-avatar>
        </div>

        <div class="avatar-test-item">
          <p>带时间戳刷新:</p>
          <el-avatar :size="80" :src="avatarUrl + '?t=' + Date.now()">
            {{ user?.nickname?.charAt(0) || 'U' }}
          </el-avatar>
        </div>
      </div>
    </div>

    <div class="test-section">
      <h4>文件上传测试</h4>
      <input
        ref="fileInput"
        type="file"
        accept="image/*"
        style="display: none"
        @change="testUpload"
      />
      <el-button @click="$refs.fileInput.click()" type="primary">
        选择图片测试上传
      </el-button>
      <p class="test-tip">选择一张小图片进行测试</p>
    </div>

    <div class="test-section">
      <h4>手动刷新测试</h4>
      <el-button @click="testRefresh" type="success">
        手动刷新头像
      </el-button>
      <el-button @click="testClear" type="warning">
        清空头像
      </el-button>
    </div>

    <div class="test-section" v-if="uploadResult">
      <h4>上次上传结果</h4>
      <pre>{{ JSON.stringify(uploadResult, null, 2) }}</pre>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useAuthStore } from '../store/authStore.js'
import { userAPI } from '../services/api.js'

export default {
  name: 'AvatarTest',
  setup() {
    const authStore = useAuthStore()
    const fileInput = ref()
    const uploadResult = ref(null)

    const user = computed(() => authStore.user.value)

    const avatarUrl = computed(() => {
      const avatar = user.value?.avatar
      if (avatar) {
        if (avatar.startsWith('http')) {
          return avatar
        }
        return userAPI.getAvatarUrl(avatar)
      }
      return null
    })

    const testUpload = async (event) => {
      const file = event.target.files[0]
      if (!file) return

      console.log('测试上传文件:', {
        name: file.name,
        size: file.size,
        type: file.type
      })

      try {
        uploadResult.value = null
        const response = await userAPI.uploadAvatar(user.value.id, file)
        console.log('上传响应:', response)
        uploadResult.value = response

        // 更新用户信息 - 支持多种响应格式
        const isSuccess = response.success ||
                         (response.message && response.message === '头像上传成功') ||
                         (response.message && response.message.includes('成功'))

        if (isSuccess) {
          // 处理不同的响应格式
          let avatarUrl = null

          if (response.avatarUrl) {
            // 格式1：直接返回头像URL
            avatarUrl = response.avatarUrl
          } else if (response.url) {
            // 格式2：返回URL字段
            avatarUrl = response.url
          } else if (response.data?.avatarUrl) {
            // 格式3：嵌套在data中
            avatarUrl = response.data.avatarUrl
          } else if (response.filename) {
            // 格式4：返回文件名，需要构建URL
            // 支持相对路径和完整URL两种格式
            if (response.filename.startsWith('http://') || response.filename.startsWith('https://')) {
              avatarUrl = response.filename
            } else {
              avatarUrl = `/api/avatars/${response.filename}`
            }
          } else if (response.data?.filename) {
            // 格式5：文件名在data中
            const filename = response.data.filename
            if (filename.startsWith('http://') || filename.startsWith('https://')) {
              avatarUrl = filename
            } else {
              avatarUrl = `/api/avatars/${filename}`
            }
          }

          if (avatarUrl) {
            // 确保avatarUrl是完整URL格式
            let finalAvatarUrl = avatarUrl

            // 处理头像URL格式，确保使用正确的路径
            if (avatarUrl.startsWith('http://') || avatarUrl.startsWith('https://')) {
              // 已经是完整URL，直接使用
              finalAvatarUrl = avatarUrl
              console.log('使用完整URL:', finalAvatarUrl)
            } else if (avatarUrl.startsWith('/api/avatars/')) {
              // 头像API路径，使用代理路径（会被代理转发到后端8081端口）
              finalAvatarUrl = avatarUrl
              console.log('使用代理路径:', finalAvatarUrl)
            } else if (avatarUrl.startsWith('/api/')) {
              // 其他API路径，直接使用
              finalAvatarUrl = avatarUrl
              console.log('使用API路径:', finalAvatarUrl)
            } else {
              // 文件名格式，构建完整代理路径
              finalAvatarUrl = `/api/avatars/${avatarUrl}`
              console.log('构建头像路径:', finalAvatarUrl)
            }

            const updatedUser = {
              ...user.value,
              avatar: finalAvatarUrl
            }
            authStore.updateUserInfo(updatedUser)
            console.log('用户信息已更新:', updatedUser)
          } else {
            console.error('无法获取头像URL，响应格式:', response)
          }
        }
      } catch (error) {
        console.error('上传失败:', error)
        uploadResult.value = { error: error.message }
      }

      // 清空文件输入
      event.target.value = ''
    }

    const testRefresh = () => {
      console.log('手动刷新头像')
      if (user.value?.avatar) {
        const currentAvatar = user.value.avatar
        const updatedUser = {
          ...user.value,
          avatar: currentAvatar + '?t=' + Date.now()
        }
        authStore.updateUserInfo(updatedUser)

        setTimeout(() => {
          const normalUser = {
            ...user.value,
            avatar: currentAvatar
          }
          authStore.updateUserInfo(normalUser)
        }, 100)
      }
    }

    const testClear = () => {
      console.log('清空头像')
      const updatedUser = {
        ...user.value,
        avatar: null
      }
      authStore.updateUserInfo(updatedUser)
    }

    return {
      user,
      avatarUrl,
      fileInput,
      uploadResult,
      testUpload,
      testRefresh,
      testClear,
      userAPI
    }
  }
}
</script>

<style scoped>
.avatar-test {
  padding: 20px;
  max-width: 1000px;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: #fafafa;
}

.test-section h4 {
  margin-top: 0;
  color: #333;
}

.avatar-tests {
  display: flex;
  gap: 30px;
  align-items: center;
  flex-wrap: wrap;
}

.avatar-test-item {
  text-align: center;
}

.avatar-test-item p {
  margin-bottom: 10px;
  font-weight: 500;
}

.test-tip {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

</style>
